package pl.un4giv3n.mightvsmagic.admin.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.ActivityType;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserActivity;
import pl.un4giv3n.mightvsmagic.entity.UserType;
import pl.un4giv3n.mightvsmagic.utils.ActivityLogUtil;

/**
 * @author andrzejewskia go-to-admin-main page action
 */
public class DeleteAdminAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * session user
	 */
	private User user;

	private long adminId;
	@Override
	public String execute() {
		EntityManager em = getEntityManager();
		user = getSessionUser(em);
		if (user == null || user.getUserType() != UserType.ADMIN) {
			addActionError("Zaloguj się");
			em.close();
			return LOGIN;
		}
		em.getTransaction().begin();
		User admin = em.find(User.class, adminId);
		if(admin != null && adminId != user.getId().longValue()){
			UserActivity activity = ActivityLogUtil.createActivity(ActivityType.ADMIN_DELETE, user.getId()," Usunięcie admina: "+ admin.toString());
			em.persist(activity);
			em.remove(admin);
			em.flush();
			em.getTransaction().commit();
			em.close();
			return SUCCESS;
		}
		em.getTransaction().rollback();
		em.close();
		return INPUT;
	}
	public long getAdminId() {
		return adminId;
	}
	public void setAdminId(long adminId) {
		this.adminId = adminId;
	}

}
